<template>
    <div class="left-container" :class="{ 'expNo': leftStatus }" v-if="!isMobile">


        <div class="left-container-title">
            <div class="titleSp">器件参数智能提取</div>
            <img @click="setLeft" class="pointer icon1" src="@/assets/images/exp.svg" alt="">

        </div>
        <div v-if="!leftStatus">
            <el-button type="primary"
                style="width: 100%;background: #1C71E6;height: 40px;font-size: 16px;border-radius: 12px;"
                @click="handleAddSession">
                新任务
            </el-button>
            <div class="hostoryDialogue flex">
                <div>
                    <img src="@/assets/images/liao.svg" alt="">

                    <span style="padding-left: 4px;">最近对话</span>
                </div>
                <div> <img class="pointer" src="@/assets/images/low.svg" alt="">
                </div>
            </div>
            <div class="session-area">
                <div>今天</div>

                <div class="session-item" :class="activeIndex == index ? 'session-item-active' : ''"
                    v-for="(item, index) in sessionList" :key="index" @click="handleChangeSessionIndex(index)">
                    <span :class="activeIndex == index ? 'active-node' : 'normal-node'" v-if="editIndex != index">{{
                        item.title }}</span>
                    <el-input :ref="`renameRef_${index}`" autofocus v-model="item.title" v-else size="small"
                        style="width: 120px" @blur="editIndex = -1" @change="editIndex = -1" />
                    <div class="icon-box">
                        <el-icon class="icon" color="#E6A23C" @click.stop="handleFocusInput(index)">
                            <Brush />
                        </el-icon>
                        <el-icon class="icon" color="#F56C6C" @click.stop="handleDeleteSession(index)">
                            <Delete />
                        </el-icon>
                    </div>
                </div>
            </div>

        </div>
        <div v-else>

            <div class="sentere"> <img src="@/assets/images/lanliao.svg" alt=""></div>
            <div class="sentere"> <img src="@/assets/images/huiliao.svg" alt=""></div>
        </div>
        <div class="flex userLow">
            <div class="sentere" style="padding-bottom: 0;"> <img src="@/assets/images/userF.svg" alt=""></div>
            <span v-if="!leftStatus">User_test</span>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import OpenAI from "openai";

import { Promotion, Delete, Brush, Top } from "@element-plus/icons-vue";
import { getTokens } from "@/api/modules/deepseek.js";
import { ElMessage, ElMessageBox } from "element-plus";
import MobileDetect from "mobile-detect";

// 响应式数据
const isMobile = ref(false);
const sessionList = ref([]);
const activeIndex = ref(-1);
const editIndex = ref(-1);
const totalAmt = ref(0);
const queryKeys = ref("");
const loading = ref(false);
const messageRef = ref(null);
const renameRefs = ref({});

// 左侧状态
const leftStatus = ref(true)

const queryInfos = ref({
    messages: [],
    model: "deepseek-chat",
    stream: true,
});



const apiKey = import.meta.env.VITE_DEEPSEEK_API_KEY;
const openai = ref(null);


const setLeft = () => {
    leftStatus.value = !leftStatus.value
}



// 初始化方法
const initSessionList = () => {
    sessionList.value = JSON.parse(localStorage.getItem("list") || "[]");
};

const initIndex = () => {
    const listLen = JSON.parse(localStorage.getItem("list") || "[]").length;
    const lastIndex = JSON.parse(localStorage.getItem("index") || "-1");

    if (listLen) {
        activeIndex.value = lastIndex || 0;
    } else {
        activeIndex.value = -1;
    }

    if (activeIndex.value != -1) {
        queryInfos.value.messages = sessionList.value[activeIndex.value]?.messages || [];
    }
};

const initOpenAI = () => {
    openai.value = new OpenAI({
        baseURL: "https://api.deepseek.com",
        apiKey: apiKey,
        dangerouslyAllowBrowser: true,
    });
};

const initToken = async () => {
    const res = await getTokens({
        deepseek: "Y",
        gptToken: apiKey,
    });
    const { balance_infos = [] } = res;
    balance_infos.forEach((o) => {
        totalAmt.value += Number(o.total_balance);
    });
};



const handleAddSession = () => {
    re
    if (loading.value) {
        ElMessage({ type: "warning", message: "请当前问题查询完成后重试！" });
        return;
    }
    sessionList.value.push({
        title: `对话${sessionList.value.length + 1}`,
        crtTime: new Date(),
        messages: [],
    });
    queryInfos.value.messages = [];
    activeIndex.value = sessionList.value.length - 1;
};

const handleDeleteSession = (index = 0) => {
    ElMessageBox.confirm("确认删除当前对话？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        sessionList.value.splice(index, 1);

        if (index == activeIndex.value) {
            activeIndex.value = sessionList.value[index] ? index : index - 1;
        } else if (index < activeIndex.value) {
            activeIndex.value--;
        }

        queryInfos.value.messages = activeIndex.value > -1 ? sessionList.value[activeIndex.value].messages : [];
        handleChangeSessionIndex(activeIndex.value);
    }).catch(() => { });
};

const handleFocusInput = (index) => {
    editIndex.value = index;
    nextTick(() => {
        renameRefs.value[`renameRef_${index}`].focus();
    });
};

const handleChangeSessionIndex = (index) => {
    if (loading.value) {
        ElMessage({ type: "warning", message: "请当前问题查询完成后重试！" });
        return;
    }
    activeIndex.value = index;
    queryInfos.value.messages = sessionList.value[activeIndex.value]?.messages || [];
    forceScrollToBottom();
};

const forceScrollToBottom = () => {
    messageRef.value?.scrollBottom(true);
};

const handleRequest = async () => {
    if (!queryKeys.value) return;
    if (!openai.value) initOpenAI();

    if (!sessionList.value.length) {
        await handleAddSession();
    }

    queryInfos.value.messages.push({
        role: "user",
        content: queryKeys.value,
    });
    queryKeys.value = "";
    forceScrollToBottom();

    try {
        loading.value = true;
        messageRef.value.isAutoScroll = true;
        const response = await openai.value.chat.completions.create(queryInfos.value);

        queryInfos.value.messages.push({ role: "assistant", content: "" });

        for await (const part of response) {
            queryInfos.value.messages[queryInfos.value.messages.length - 1].content += part.choices[0]?.delta?.content || "";
            messageRef.value?.scrollBottom();
        }

        messageRef.value?.scrollBottom();
        sessionList.value[activeIndex.value].messages = queryInfos.value.messages;
    } catch (error) {
        queryInfos.value.messages.push({
            role: "assistant",
            content: "加载失败,请稍后重试!",
        });
    } finally {
        loading.value = false;
    }
};

// 生命周期
onMounted(() => {
    // 设备检测
    const md = new MobileDetect(window.navigator.userAgent);
    isMobile.value = !!md.mobile();

    // 回车事件监听
    const keyInput = document.getElementById("keyInput");
    if (keyInput) {
        keyInput.addEventListener("keydown", (event) => {
            if (event.key === "Enter") {
                handleRequest();
                event.preventDefault();
            }
        });
    }

    forceScrollToBottom();
});

// 初始化
initSessionList();
initIndex();
initOpenAI();
initToken();

// 监听器
watch([sessionList, activeIndex], () => {
    const list = sessionList.value.map((o, i) => {
        if (i == activeIndex.value) {
            return {
                ...o,
                messages: queryInfos.value.messages,
            };
        }
        return { ...o };
    });

    localStorage.setItem("list", JSON.stringify(list));
    localStorage.setItem("index", JSON.stringify(activeIndex.value));
}, { deep: true });
</script>

<style scoped lang="scss">
.flex {
    display: flex;
    justify-content: space-between;
}


.userLow {
    position: absolute;
    // left: 0;
    // right: 0;
    bottom: 0;
    justify-self: start;
    align-items: center;
    padding: 16px;
    // background: rgb(216.8, 235.6, 255);
    // .sentere{
    //   padding-bottom: 0 !important;
    // }

    span {
        padding-left: 16px;
    }
}

/* 样式部分保持不变 */
.pointer {
    cursor: pointer;
}

.no-border {
    border: none !important;
}


.left-container {
    background-color: #F0F4F8;
    padding: 0px 16px;
    height: 100%;
    width: 300px;
    transition: width 0.3s ease;

    position: relative;

    &.expNo {
        width: 60px;

        .icon1 {
            transform: rotate(180deg);
        }

        .titleSp {
            display: none;
        }

        .left-container-title {
            justify-content: center;
        }

        .sentere {
            display: flex;
            justify-content: center;
            padding-bottom: 16px;
        }
    }

    .left-container-title {
        display: flex;
        justify-content: space-between;
        padding: 22px 0px;
        align-items: center;

        .titleSp {
            font-size: 20px;
            font-weight: 600;
            color: #333333;
        }
    }

    .hostoryDialogue {
        // display: ;
        font-size: 16px;
        color: #333333;
        align-items: center;
        padding: 20px 0;

        &>div {
            display: flex;
            align-items: center;
        }
    }

    .session-area {
        width: 100%;
        height: calc(90vh - 32px - 24px - 12px - 32px);
        margin-top: 12px;
        box-sizing: border-box;
        overflow-y: auto;

        .session-item {
            height: 36px;
            line-height: 36px;
            margin-bottom: 8px;
            border-radius: 4px;
            padding: 0 18px;
            // background: rgb(199.5, 201, 204);
            color: #666666;
            font-size: 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            cursor: pointer;

            .normal-node {
                padding-left: 14px;
            }

            .icon-box {
                visibility: hidden;
                display: grid;
                column-gap: 8px;
                grid-template-columns: repeat(2, 1fr);

                .icon {
                    cursor: pointer;
                }
            }

            &:hover .icon-box {
                visibility: visible;
            }
        }

        .session-item-active {
            border-radius: 12px;
            opacity: 1;
            color: #333333;
            background: #FFFFFF;
            font-size: 16px;
            box-shadow: 0px 2px 4px 0px rgba(11, 45, 92, 0.05);


            .active-node {
                display: flex;
                align-items: center;

                &::before {
                    display: inline-block;
                    content: "";
                    width: 6px;
                    height: 6px;
                    background: #fff;
                    border-radius: 50%;
                    margin-right: 8px;
                }
            }
        }
    }
}
</style>
